package utils

import (
	"strings"
)

type mapping struct {
	dbTypeName      []string // 数据库类型名称
	notNullTypeName string   // 不为空时的类型名称
	nullTypeName    string   // 为空时的类型名称
}

var myConf = []mapping{
	{
		dbTypeName: []string{
			"character",
			"character varying",
			"char",
			"varchar",
			"text",
			"money",
			"interval",
			"json",
			"jsonb",
			"xml",
		},
		notNullTypeName: "string",
		nullTypeName:    "sql.NullString",
	},
	{
		dbTypeName: []string{
			"time with time zone",
			"time without time zone",
			"timestamp without time zone",
			"timestamp with time zone",
			"date",
		},
		notNullTypeName: "time.Time",
		nullTypeName:    "sql.NullTime",
	},
	{
		dbTypeName: []string{
			"boolean",
		},
		notNullTypeName: "bool",
		nullTypeName:    "sql.NullBool",
	},
	{
		dbTypeName: []string{
			"smallint",
		},
		notNullTypeName: "int16",
		nullTypeName:    "sql.NullInt32",
	},
	{
		dbTypeName: []string{
			"smallserial",
		},
		notNullTypeName: "int16",
		nullTypeName:    "int16",
	},
	{
		dbTypeName: []string{
			"integer",
		},
		notNullTypeName: "int32",
		nullTypeName:    "sql.NullInt32",
	},
	{
		dbTypeName: []string{
			"serial",
		},
		notNullTypeName: "int32",
		nullTypeName:    "int32",
	},
	{
		dbTypeName: []string{
			"bigint",
		},
		notNullTypeName: "int64",
		nullTypeName:    "sql.NullInt64",
	},
	{
		dbTypeName: []string{
			"bigserial",
		},
		notNullTypeName: "int64",
		nullTypeName:    "int64",
	},
	{
		dbTypeName: []string{
			"real",
		},
		notNullTypeName: "float32",
		nullTypeName:    "sql.NullFloat64",
	},
	{
		dbTypeName: []string{
			"decimal",
			"numeric",
			"double precision",
		},
		notNullTypeName: "float64",
		nullTypeName:    "sql.NullFloat64",
	},
	{
		dbTypeName: []string{
			"bytea",
		},
		notNullTypeName: "[]byte",
		nullTypeName:    "[]byte",
	},
}

// PostgreSQL数据类型
// https://www.w3cschool.cn/qysrc/qysrc-ev1d375d.html
func Mapping(typeName string, notNull bool) string {
	// 有的类型有长度，所以先去掉长度
	lastIndex := strings.LastIndex(typeName, "(")
	if lastIndex != -1 {
		typeName = typeName[0:lastIndex]
	}

	for _, conf := range myConf {
		for _, name := range conf.dbTypeName {
			// 匹配到了
			if name == typeName {
				if notNull {
					return conf.notNullTypeName
				}
				return conf.nullTypeName
			}
		}
	}
	return "interface{}"
}
